//
// StatusJig
//
// Copyright (C) jextra.net.
//
//  This file is part of the Nubbin Library.
//
//  The Nubbin Library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  The Nubbin Library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with the Nubbin Library; if not, write to the Free
//  Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
//  02111-1307 USA.
//

package net.jextra.nubbinstoreweb.jig;

import java.io.*;
import java.net.*;
import java.util.*;
import net.jextra.jig.*;
import net.jextra.nubbin.store.*;
import net.jextra.nubbin.store.http.*;

@JigDef( description = "Get status of files from NubbinStore." )
public class StatusJig implements Jig
{
    // ============================================================
    // Fields
    // ============================================================

    public static final int BUFFER_SIZE = 10000;

    @JigField( "URL:" )
    private String _url;

    @JigField( "Local Dir:" )
    private String _localDir;

    private NubbinStoreEntriesReader _reader;

    // ============================================================
    // Methods
    // ============================================================

    // ----------
    // public
    // ----------

    @JigCommand( "Synchronize" )
    public void synch()
        throws Exception
    {
        boolean success = getStatus();
        if ( success )
        {
            downloadOutdatedFiles();
            writeProps();
        }
        else
        {
            System.out.println( "Unable to communicate with NubbinStore." );
        }
    }

    @JigCommand( "Get Status" )
    public boolean getStatus()
        throws Exception
    {
        URLConnection conn = getURL( "status.xml" ).openConnection();
        try
        {
            conn.connect();
        }
        catch ( Throwable ex )
        {
            // Failed to communicate with store.
            return false;
        }
        InputStream in = conn.getInputStream();

        _reader = new NubbinStoreEntriesReader();
        _reader.parse( in );
        for ( NubbinStoreEntry entry : _reader.getEntries() )
        {
            System.out.println( entry.getPath() + " " + entry.getTimestamp() );
        }

        in.close();
        return true;
    }

    @JigCommand( "Show Diffs" )
    public void showDiffs()
        throws Exception
    {
        Properties props = new Properties();
        File file = new File( "crackpluginstore.properties" );
        if ( file.exists() )
        {
            props.load( new FileInputStream( file ) );
        }

        System.out.println( "========================================" );
        for ( NubbinStoreEntry entry : _reader.getEntries() )
        {
            String value = props.getProperty( entry.getPath() );
            if ( value != null )
            {
                long timestamp = Long.parseLong( value );
                if ( timestamp == entry.getTimestamp() )
                {
                    continue;
                }
            }

            System.out.println( entry.getPath() + " " + entry.getTimestamp() );
        }
    }

    @JigCommand( "Download" )
    public void downloadOutdatedFiles()
        throws Exception
    {
        Properties props = new Properties();
        File propsFile = new File( "crackpluginstore.properties" );
        if ( propsFile.exists() )
        {
            props.load( new FileInputStream( propsFile ) );
        }

        System.out.println( "========================================" );
        for ( NubbinStoreEntry entry : _reader.getEntries() )
        {
            File file = new File( _localDir, entry.getPath() );

            String value = props.getProperty( entry.getPath() );
            if ( file.exists() && value != null )
            {
                long timestamp = Long.parseLong( value );
                if ( timestamp == entry.getTimestamp() )
                {
                    // Timestamp is the same, no need to download.
                    continue;
                }
            }

            System.out.println( "Writing " + entry.getPath() );
            downloadFile( entry.getPath() );
        }
    }

    @JigCommand( "Write Properties" )
    public void writeProps()
        throws Exception
    {
        Properties props = new Properties();

        for ( NubbinStoreEntry entry : _reader.getEntries() )
        {
            props.setProperty( entry.getPath(), "" + entry.getTimestamp() );
            System.out.println( entry.getPath() + " " + entry.getTimestamp() );
        }

        File file = new File( "crackpluginstore.properties" );
        props.store( new FileOutputStream( file ),
            "Crack Plugin Store synchronization timestamps" );
    }

    // ----------
    // private
    // ----------

    private URL getURL( String relativeURL )
        throws MalformedURLException
    {
        String url = _url.replace( '\\', '/' );
        if ( !url.endsWith( "/" ) )
        {
            url += "/";
        }
        url += relativeURL;

        return new URL( url );
    }

    private void downloadFile( String path )
        throws MalformedURLException, IOException
    {
        URL url = getURL( "download?path=" + path );
        URLConnection conn = url.openConnection();
        System.out.println( url.toString() );
        conn.connect();
        InputStream in = conn.getInputStream();

        File file = new File( _localDir, path );
        file.getParentFile().mkdirs();
        FileOutputStream out = new FileOutputStream( file );

        byte[] buf = new byte[BUFFER_SIZE];
        int i = 0;
        while ( ( i = in.read( buf ) ) != -1 )
        {
            out.write( buf, 0, i );
        }
        in.close();
        out.close();
    }
}

